package org.wisdom.service.impl;

import org.apache.coyote.BadRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.wisdom.entity.User;
import org.wisdom.mapper.AuthMapper;
import org.wisdom.mapstruct.UserMapStruct;
import org.wisdom.request.LoginRequest;
import org.wisdom.request.RegisterRequest;
import org.wisdom.service.AuthService;
import org.wisdom.utils.JwtUtils;
import org.wisdom.utils.SnowflakeUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthMapper authMapper;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private SnowflakeUtils snowflakeUtils;

    private static final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public String login(LoginRequest loginRequest) throws BadRequestException {
        // 从数据库获取密码(和id)
        User user = authMapper.selectPasswordByPhoneNumber(loginRequest.getPhoneNumber());
        if (user == null) {
            throw new BadRequestException("用户不存在或密码错误！");
        }

        // 密码校验
        if (!passwordEncoder.matches(loginRequest.getPassword(), user.getEncodedPassword())) {
            throw new BadRequestException("用户不存在或密码错误！");
        }

        // 校验成功, 生成令牌
        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        return jwtUtils.generateJwt(map);
    }

    @Override
    public void register(RegisterRequest registerRequest) throws BadRequestException {
        if (authMapper.selectPhoneNumberIsExist(registerRequest.getPhoneNumber())) {
            throw new BadRequestException("手机号已被注册！");
        }

        User user = UserMapStruct.INSTANCE.registerRequestToUser(registerRequest);
        user.setId(snowflakeUtils.nextId());
        user.setEncodedPassword(passwordEncoder.encode(registerRequest.getPassword()));
        user.setCreatedTime(LocalDateTime.now());
        authMapper.insertToRegister(user);
    }
}
